package com.sumer.brain.common.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.sumer.brain.common.constant.SystemConstant;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * com.alibaba.easyexcel 的工具类
 */
public class EasyExcelUtil {

    /**
     * 简单读取 Excel 文件。
     *
     * @param fileName     Excel 文件路径
     * @param clazz        数据模型类
     * @param readListener 读取监听器
     */
    public static <T> void simpleRead(String fileName, Class<T> clazz, ReadListener<T> readListener) {
        if (fileName == null || fileName.trim().isEmpty()) {
            throw new IllegalArgumentException("File name cannot be empty.");
        }
        if (clazz == null) {
            throw new IllegalArgumentException("Class cannot be null.");
        }
        if (readListener == null) {
            throw new IllegalArgumentException("ReadListener cannot be null.");
        }
        try {
            EasyExcel.read(fileName, clazz, readListener).sheet().doRead();
        } catch (Exception e) {
            throw new RuntimeException("Error reading E xcel file: " + e.getMessage());
        }
    }

    public static <T> List<T> simpleReadSync(String filename, Class<T> clazz) {
        return EasyExcel.read(filename).head(clazz).sheet().doReadSync();
    }

    public static <T> void simpleWrite(HttpServletResponse response, String fileName, Class<T> clazz, List<T> data, String sheetName) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding(SystemConstant.UTF8);
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 这里需要设置不关闭流
        EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(data);
    }

}

